package cn.com.do1.component.merchant.merchant.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.exception.IllegalParameterException;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.component.merchandise.merchandise.model.TbCzMerchandisePO;
import cn.com.do1.component.merchandise.merchandise.service.IMerchandiseService;
import cn.com.do1.component.merchandise.merchandise.vo.TbCzMerchandiseVO;
import cn.com.do1.component.merchant.merchant.model.*;
import cn.com.do1.component.merchant.merchant.service.IMerchantService;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantVO;
import cn.com.do1.component.pay.pay.model.TbCzPayPO;
import cn.com.do1.component.pay.pay.service.IPayService;
import cn.com.do1.component.pay.pay.vo.TbCzPayClientVO;
import cn.com.do1.component.pay.pay.vo.TbCzPayVO;
import cn.com.do1.component.systemmgr.person.model.PersonVO;
import cn.com.do1.component.systemmgr.person.model.TbDqdpPersonPO;
import cn.com.do1.component.systemmgr.person.service.IPersonService;
import cn.com.do1.component.systemmgr.user.model.BaseUserVO;
import cn.com.do1.component.systemmgr.user.model.User;
import cn.com.do1.component.systemmgr.user.model.UserVO;
import cn.com.do1.component.systemmgr.role.model.TbDqdpRolePO;
import cn.com.do1.component.systemmgr.role.service.IRoleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.tools.ant.types.CommandlineJava.SysProperties;

import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.sql.SQLException;
import java.text.DecimalFormat;

import cn.com.do1.common.util.AssertUtil;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.common.util.reflation.BeanHelper;
import cn.com.do1.common.util.reflation.ClassTypeUtil;
import cn.com.do1.common.util.security.SecurityUtil;
import cn.com.do1.dqdp.core.ConfigMgr;
import cn.com.do1.dqdp.core.DqdpAppContext;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.support.AbstractInterruptibleBatchPreparedStatementSetter;
import org.springframework.security.authentication.BadCredentialsException;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司 All rights reserved. User: ${user}
 */
public class MyInfoAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(MyInfoAction.class);

    private TbCzMerchantPO tbCzMerchantPO;
    private TbCzMerchantVO merchantVO;
    private String ids[];
    private String id;
    private PersonVO personVO;
    private UserVO userVO;
    private BaseUserVO baseUserVO;
    private Map myPersonMap;
    private String personId;
    private String userId;
    private String password;
    private String newPassword;
    private String orgId;
    private TbCzPayPO tbCzPayPO;

    private IMerchantService merchantService;

    private IPersonService myPersonService;

    @Resource
    private IMerchandiseService merchandiseService;

    @Resource
    private IRoleService roleService;

    @Resource
    private IPayService payService;

    @Resource
    public void setMerchantService(IMerchantService merchantService) {
        this.merchantService = merchantService;
    }

    @Resource
    public void setMyPersonService(IPersonService myPersonService) {
        this.myPersonService = myPersonService;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


    public PersonVO getPersonVO() {
        return personVO;
    }

    public void setPersonVO(PersonVO personVO) {
        this.personVO = personVO;
    }

    public UserVO getUserVO() {
        return userVO;
    }

    public void setUserVO(UserVO userVO) {
        this.userVO = userVO;
    }

    public BaseUserVO getBaseUserVO() {
        return baseUserVO;
    }

    public void setBaseUserVO(BaseUserVO baseUserVO) {
        this.baseUserVO = baseUserVO;
    }

    public Map getMyPersonMap() {
        return myPersonMap;
    }

    public void setMyPersonMap(Map myPersonMap) {
        this.myPersonMap = myPersonMap;
    }

    public TbCzMerchantPO getTbCzMerchantPO() {
        return tbCzMerchantPO;
    }


    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }


    public TbCzMerchantVO getMerchantVO() {
        return merchantVO;
    }

    public void setMerchantVO(TbCzMerchantVO merchantVO) {
        this.merchantVO = merchantVO;
    }


    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public TbCzPayPO getTbCzPayPO() {
        return tbCzPayPO;
    }

    public void setTbCzPayPO(TbCzPayPO tbCzPayPO) {
        this.tbCzPayPO = tbCzPayPO;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "testNumber", type = "number"),
            @SearchValueType(name = "testString", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = merchantService.searchMerchant(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        // todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        // todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        // 完成批量更新的代码
    }

    public void setTbCzMerchantPO(TbCzMerchantPO tbCzMerchantPO) {
        this.tbCzMerchantPO = tbCzMerchantPO;
    }

    public TbCzMerchantPO setTbCzMerchantPO() {
        return this.tbCzMerchantPO;
    }

    public void addTbCzMerchantPO() {
        super.ajaxAdd(tbCzMerchantPO);
    }

    public void updateTbCzMerchantPO() {
        super.ajaxUpdate(tbCzMerchantPO);
    }

    public void deleteTbCzMerchantPO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbCzMerchantPO._setPKValue(id);
        super.ajaxDelete(tbCzMerchantPO);
    }

    public void batchDeleteTbCzMerchantPO() {
        super.ajaxBatchDelete(TbCzMerchantPO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxView() throws Exception, BaseException {

        TbCzMerchantPO xxPO = merchantService.searchByPk(TbCzMerchantPO.class, id);
        addJsonFormateObj("tbCzMerchantPO", xxPO);// 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    @ActionRoles({"userAdd"})
    public void addPerson() {
        try {
            merchantService.addPerson(personVO, userVO, merchantVO, myPersonMap);
            setActionResult("0", "新增人员信息成功");
        } catch (SQLException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        } catch (Exception e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        } catch (BaseException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        }
        doJsonOut();
    }

    @ActionRoles({"myUserInfoView"})
    public void viewBaseUserDetailVO() {

        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能查看信息");
        } else {
            this.personId = user.getPersonId();

            try {
                addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
                addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
                addJsonObj("merchantVO", this.merchantService.getMerchantDetailByPersonId(this.personId));
                setActionResult("0", "查询成功");
            } catch (BaseException e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            } catch (Exception e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"myUserInfoView"})
    public void viewBaseUserVO() {
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能查看信息");
        } else {
            this.personId = user.getPersonId();

            try {
                addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
                addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
                addJsonObj("merchantVO", this.merchantService.getMerchantByPersonId(this.personId));
                setActionResult("0", "查询成功");
            } catch (BaseException e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            } catch (Exception e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"myAdminUserInfoView"})
    public void viewAdminBaseUserDetailVO() {

        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能查看信息");
        } else {
            this.personId = user.getPersonId();

            try {
                addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
                addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
                addJsonObj("merchantVO", this.merchantService.getMerchantDetailByPersonId(this.personId));
                setActionResult("0", "查询成功");
            } catch (BaseException e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            } catch (Exception e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"myAdminUserInfoView"})
    public void viewAdminBaseUserVO() {
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能查看信息");
        } else {
            this.personId = user.getPersonId();

            try {
                addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
                addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
                addJsonObj("merchantVO", this.merchantService.getMerchantByPersonId(this.personId));
                setActionResult("0", "查询成功");
            } catch (BaseException e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            } catch (Exception e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"userDel"})
    public void delPerson() {
        try {
            this.merchantService.delPerson(this.ids);
            setActionResult("0", "删除人员信息成功");
        } catch (Exception e) {
            logger.error("删除人员记录时发生异常", e);
            setActionResult("1914", "删除人员信息失败");
        } catch (BaseException e) {
            logger.error("删除人员记录时发生异常", e);
            setActionResult("1914", "删除人员信息失败");
        }
        doJsonOut();
    }

    @ActionRoles({"userDel"})
    public void delBaseUser() {
        try {
            this.merchantService.delBaseUserByPersonId(this.ids);
            setActionResult("0", "删除用户成功");
        } catch (Exception e) {
            logger.error("删除用户异常", e);
            setActionResult("1001", "删除失败");
        } catch (BaseException e) {
            logger.error("删除用户异常", e);
            setActionResult("1001", "删除失败");
        }
        doJsonOut();
    }

    @ActionRoles({"myUserInfoEdit"})
    public void updateBaseUser() {
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能更新信息");
        } else {
            try {
                this.merchantVO.setOper(user.getUsername());
                this.merchantVO.setUpdateDate(DateUtil.formartCurrentDateTime());
                this.merchantVO.setDiscount(null);
                this.merchantVO.setPayPassword(null);
                this.merchantVO.setUserId(null);
                this.merchantVO.setMoney(null);// 防止修改不能修改的数据
                this.merchantService.updateBaseUser(this.baseUserVO, this.merchantVO, this.myPersonMap);
                setActionResult("0", "修改用户信息成功");
            } catch (BaseException e) {
                logger.error("修改用户信息异常", e);
                setActionResult("1001", "修改用户信息失败");
            } catch (Exception e) {
                logger.error("修改用户信息异常", e);
                setActionResult("1001", "修改用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"myAdminUserInfoEdit"})
    public void updateAdminBaseUser() {
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能更新信息");
        } else {
            try {
                this.merchantVO.setOper(user.getUsername());
                this.merchantVO.setUpdateDate(DateUtil.formartCurrentDateTime());
                this.merchantVO.setDiscount(null);
                this.merchantVO.setPayPassword(null);
                this.merchantVO.setUserId(null);
                this.merchantVO.setMoney(null);// 防止修改不能修改的数据
                this.merchantService.updateBaseUser(this.baseUserVO, this.merchantVO, this.myPersonMap);
                setActionResult("0", "修改信息成功");
            } catch (BaseException e) {
                logger.error("修改信息异常", e);
                setActionResult("1001", "修改信息失败");
            } catch (Exception e) {
                logger.error("修改用户信息异常", e);
                setActionResult("1001", "修改信息失败");
            }
        }
        doJsonOut();
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "凭证密码修改失败", successMsg = "凭证密码修改成功"))
    @ActionRoles("changePayPassword")
    public void changePayPassword() throws Exception, BaseException {

        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "新凭证密码不能为空");
        } else {
            try {

                User user = (User) DqdpAppContext.getCurrentUser();
                TbCzMerchantVO vo = this.merchantService.getMerchantByPersonId(user.getPersonId());
                if (SecurityUtil.getMd5Code(password).equals(vo.getPayPassword())) {
                    this.merchantService.changePayPassword(user.getId(), this.newPassword);
                    setActionResult("0", "修改凭证密码成功");
                } else {
                    setActionResult("1001", "原凭证密码不正确");
                }

            } catch (BaseException e) {
                logger.error("修改凭证密码异常", e);
                setActionResult("1001", "修改凭证密码失败");
            } catch (Exception e) {
                logger.error("修改凭证密码异常", e);
                setActionResult("1001", "修改凭证密码失败");
            }
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "支付密码修改失败", successMsg = "支付密码修改成功"))
    @ActionRoles("changePayPassword")
    public void mychangePayPassword() throws Exception, BaseException {

        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "支付密码不能为空");
        } else {
            try {

                User user = (User) DqdpAppContext.getCurrentUser();
                TbCzMerchantVO vo = this.merchantService.getMerchantByPersonId(user.getPersonId());
                if (SecurityUtil.getMd5Code(password).equals(vo.getPayPassword())) {
                    this.merchantService.changePayPassword(user.getId(), this.newPassword);
                    setActionResult("0", "修改支付密码成功");
                } else {
                    setActionResult("1001", "原支付密码不正确");
                }

            } catch (BaseException e) {
                logger.error("修改支付密码异常", e);
                setActionResult("1001", "修改支付密码失败");
            } catch (Exception e) {
                logger.error("修改支付信息异常", e);
                setActionResult("1001", "修改支付密码失败");
            }
        }
    }

    @ActionRoles({"userList"})
    @SearchValueTypes({@SearchValueType(name = "userName", type = "String", format = "%%%s%%"),
            @SearchValueType(name = "mobile", type = "String", format = "%%%s%%"),
            @SearchValueType(name = "personName", type = "String", format = "%%%s%%")})
    public void listPersonByOrgId() {
        Pager pager = new Pager(ServletActionContext.getRequest(), BaseAction.getPageSize());
        try {
            pager = this.merchantService.listPersonByOrg(this.orgId, pager, getSearchValue());
            addJsonPager("userPager", pager);
            setActionResult("0", "查询成功");
        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
            setActionResult("1001", "查询异常");
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
            setActionResult("1001", "查询异常");
        }
        doJsonOut();
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "注册失败", successMsg = "注册成功"))
    public void addMerchant() {

        HttpServletRequest httpservletrequest = ServletActionContext.getRequest();
        String randomCode = httpservletrequest.getParameter("j_code");

        String sessionCode = (String) httpservletrequest.getSession().getAttribute("RandString");

        if (randomCode == null || !randomCode.equalsIgnoreCase(sessionCode)) {
            logger.debug("------->>验证码错误");
            setActionResult("1001", "验证码错误");
        }

        String j_username = httpservletrequest.getParameter("j_username");
        ;
        String j_password = httpservletrequest.getParameter("j_password");
        ;
        String j_confirmPassword = httpservletrequest.getParameter("j_confirmPassword");
        ;
        String j_payPassword = httpservletrequest.getParameter("j_payPassword");
        ;
        String j_confirmPayPassword = httpservletrequest.getParameter("j_confirmPayPassword");
        ;
        String j_mobile = httpservletrequest.getParameter("j_mobile");
        ;
        String j_qq = httpservletrequest.getParameter("j_qq");
        String userIds = httpservletrequest.getParameter("userIds");
        String orgId = httpservletrequest.getParameter("orgId");
        String roleIds = httpservletrequest.getParameter("roleIds");
        String isInternal = httpservletrequest.getParameter("isInternal");


        this.personVO = new PersonVO();
        this.personVO.setOrgId(orgId);
        this.personVO.setPersonName(j_username);

        this.userVO = new UserVO();
        this.userVO.setUserName(j_username);
        this.userVO.setPassword(j_password);
        this.userVO.setConfirmPassword(j_confirmPassword);
        this.userVO.setIsInternal(isInternal);
        this.userVO.setRoleIds(roleIds);


        this.merchantVO = new TbCzMerchantVO();
        this.merchantVO.setPayPassword(j_payPassword);
        this.merchantVO.setMobile(j_mobile);
        this.merchantVO.setQq(j_qq);

        try {

            merchantService.addPerson(personVO, userVO, merchantVO, myPersonMap);
            setActionResult("0", "新增人员信息成功");
        } catch (SQLException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        } catch (Exception e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        } catch (BaseException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", "添加人员信息失败");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "初始化失败", successMsg = "初始化成功"))
    public void initPay() {
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            setActionResult("1001", "超级管理员不能充值套餐");
        } else {

            try {
                TbCzMerchantVO merchant = merchantService.getMerchantByUserID(user.getId());
                List<TbCzMerchandiseVO> list = merchandiseService.getUseMerchandise();
                for (TbCzMerchandiseVO tbCzMerchandiseVO : list) {

                    // 折扣后的价格
                    float resultMoney =
                            Float.parseFloat(merchant.getDiscount())
                                    * Float.parseFloat(tbCzMerchandiseVO.getMerMoney());

                    tbCzMerchandiseVO.setMerDiscountMoney(new DecimalFormat("0.00").format(resultMoney));
                }
                addJsonArray("merchandiseList", list);
                addJsonObj("merchant", merchant);

            } catch (Exception e) {
                setActionResult("1913", "初始化充值数据错误");
                logger.error("初始化充值数据错误", e);
            } catch (BaseException e) {
                setActionResult("1913", "初始化充值数据错误");
                logger.error("初始化充值数据错误", e);
            }
        }
    }

    public void addPay() {

        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "支付密码不能为空");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO)) {
            setActionResult("1001", "代理商充值数据错误");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO.getPayMerchandiseId())) {
            setActionResult("1001", "套餐类型不能为空");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO.getPayMoblie())) {
            setActionResult("1001", "充值手机号码不能为空");
        } else {


            User user = (User) DqdpAppContext.getCurrentUser();
            try {
                TbCzMerchantVO merchant = merchantService.getMerchantByUserID(user.getId());
                String passwordMD5 = SecurityUtil.getMd5Code(newPassword);
                if (passwordMD5.equals(merchant.getPayPassword())) {
                    Float money = Float.valueOf(merchant.getMoney());// 余额

                    TbCzMerchandisePO merchandise =
                            merchantService.searchByPk(TbCzMerchandisePO.class, this.tbCzPayPO.getPayMerchandiseId());

                    Float payMoney = merchandise.getMerMoney() * Float.valueOf(merchant.getDiscount());
                    payMoney = Float.valueOf(new DecimalFormat("0.00").format(payMoney));
                    if (money < payMoney) {
                        setActionResult("1001", "您账户余额:" + money + " 本次充值需要金额:" + payMoney + "，余额不足，请充值再操作");
                    } else {
                        this.tbCzPayPO.setPayDiscountMoney(payMoney);
                        this.tbCzPayPO.setPayMerchatId(user.getId());
                        this.tbCzPayPO.setPayOper(user.getUsername());
                        this.tbCzPayPO.setPayOriginalMoney(merchandise.getMerMoney());
                        this.tbCzPayPO.setPayStartDate(new Date());
                        this.tbCzPayPO.setPayStatus("1");
                        this.payService.addPay(this.tbCzPayPO);
                        setActionResult("0", "充流量提交成功");
                    }

                } else {
                    setActionResult("1001", "支付密码不正确");
                }

            } catch (SQLException e) {
                setActionResult("1913", "代理商充值数据错误");
                logger.error("代理商充值数据错误", e);
            } catch (Exception e) {
                logger.error("代理商充值数据错误", e);
                setActionResult("1913", "代理商充值数据错误");
            } catch (BaseException e) {
                setActionResult("1913", "初始化充值数据错误");
                logger.error("初始化充值数据错误", e);
            }
        }

        doJsonOut();
    }

    public void addBatchPay() {

        StringBuilder sb = new StringBuilder();// 充值结果总和

        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "支付密码不能为空");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO)) {
            setActionResult("1001", "代理商充值数据错误");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO.getPayMoblie())) {
            setActionResult("1001", "充值格式不能为空");
        } else {


            User user = (User) DqdpAppContext.getCurrentUser();
            try {
                TbCzMerchantVO merchant = merchantService.getMerchantByUserID(user.getId());
                String passwordMD5 = SecurityUtil.getMd5Code(newPassword);
                if (passwordMD5.equals(merchant.getPayPassword())) {
                    Float money = Float.valueOf(merchant.getMoney());// 余额

                    List<TbCzMerchandiseVO> useMerchandise = this.merchandiseService.getUseMerchandise();
                    List<TbCzPayPO> payList = new ArrayList<TbCzPayPO>();

                    String content = this.tbCzPayPO.getPayMoblie();
                    Date now = new Date();
                    String[] contents = content.split("\n");
                    for (String string : contents) {
                        String[] pos = string.split(" ");
                        TbCzPayPO po = new TbCzPayPO();
                        po.setPayMoblie(pos[0]);

                        boolean isOK = false;
                        for (TbCzMerchandiseVO merchandiseVO : useMerchandise) {
                            if (pos[1].equals(merchandiseVO.getMerName())) {
                                Float payMoney =
                                        Float.parseFloat(merchandiseVO.getMerMoney())
                                                * Float.valueOf(merchant.getDiscount());
                                payMoney = Float.valueOf(new DecimalFormat("0.00").format(payMoney));
                                po.setPayDiscountMoney(payMoney);
                                po.setPayMerchatId(user.getId());
                                po.setPayMerchandiseId(merchandiseVO.getMerId());
                                po.setPayOper(user.getUsername());
                                po.setPayOriginalMoney(Float.parseFloat(merchandiseVO.getMerMoney()));
                                po.setPayStartDate(now);
                                po.setPayStatus("1");
                                isOK = true;
                                payList.add(po);
                                break;
                            }
                        }
                        if (!isOK) {
                            String resultFormat =
                                    "<div>手机号码：%s<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                            resultFormat = String.format(resultFormat, pos[0], "失败，找不到对应的套餐");
                            sb.append(resultFormat);
                        }
                    }

                    Float sumPayMoney = 0f;
                    for (TbCzPayPO po : payList) {
                        sumPayMoney += po.getPayDiscountMoney();
                    }

                    if (money < sumPayMoney) {

                        setActionResult("1001", "您账户余额:" + money + " 本次批量充值需要金额:" + sumPayMoney + "，余额不足，请充值再操作");
                    } else {
                        // 支付
                        for (TbCzPayPO po : payList) {
                            try {
                                this.payService.addPay(po);
                                String resultFormat =
                                        "<div>手机号码：%s<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                                resultFormat = String.format(resultFormat, po.getPayMoblie(), "充值成功");
                                sb.append(resultFormat);
                            } catch (Exception e) {
                                logger.error("代理商充值数据错误", e);
                                String resultFormat =
                                        "<div>手机号码：%s<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                                resultFormat = String.format(resultFormat, po.getPayMoblie(), "充值失败");
                                sb.append(resultFormat);
                            } catch (BaseException e) {
                                logger.error("代理商充值数据错误", e);
                                String resultFormat =
                                        "<div>%s %s<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                                resultFormat = String.format(resultFormat, po.getPayMoblie(), "充值失败");
                                sb.append(resultFormat);
                            }

                        }
                        setActionResult("0", "充流量提交成功");
                        addJsonObj("sumPayMoney", sumPayMoney);
                    }

                } else {
                    setActionResult("1001", "支付密码不正确");
                }

            } catch (SQLException e) {
                setActionResult("1913", "代理商充值数据错误");
                logger.error("代理商充值数据错误", e);
            } catch (Exception e) {
                logger.error("代理商充值数据错误", e);
                setActionResult("1913", "代理商充值数据错误");
            } catch (BaseException e) {
                setActionResult("1913", "代理商充值数据错误");
                logger.error("代理商充值数据错误", e);
            }
        }

        addJsonObj("result", sb.toString());
        doJsonOut();
    }

    public void addInitBatchPay() {

        StringBuilder sb = new StringBuilder();// 充值结果总和

        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "支付密码不能为空");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO)) {
            setActionResult("1001", "代理商充值数据错误");
        } else if (AssertUtil.isEmpty(this.tbCzPayPO.getPayMoblie())) {
            setActionResult("1001", "充值格式不能为空");
        } else {


            User user = (User) DqdpAppContext.getCurrentUser();
            try {
                TbCzMerchantVO merchant = merchantService.getMerchantByUserID(user.getId());
                String passwordMD5 = SecurityUtil.getMd5Code(newPassword);
                if (passwordMD5.equals(merchant.getPayPassword())) {
                    Float money = Float.valueOf(merchant.getMoney());// 余额

                    List<TbCzMerchandiseVO> useMerchandise = this.merchandiseService.getUseMerchandise();
                    List<TbCzPayPO> payList = new ArrayList<TbCzPayPO>();

                    String content = this.tbCzPayPO.getPayMoblie();
                    Date now = new Date();
                    String[] contents = content.split("\n");
                    for (String string : contents) {
                        String[] pos = string.split(" ");
                        TbCzPayPO po = new TbCzPayPO();
                        po.setPayMoblie(pos[0]);

                        boolean isOK = false;
                        for (TbCzMerchandiseVO merchandiseVO : useMerchandise) {
                            if (pos[1].equals(merchandiseVO.getMerName())) {
                                Float payMoney =
                                        Float.parseFloat(merchandiseVO.getMerMoney())
                                                * Float.valueOf(merchant.getDiscount());
                                payMoney = Float.valueOf(new DecimalFormat("0.00").format(payMoney));
                                po.setPayDiscountMoney(payMoney);
                                po.setPayMerchatId(user.getId());
                                po.setPayMerchandiseId(merchandiseVO.getMerId());
                                po.setPayOper(user.getUsername());
                                po.setPayOriginalMoney(Float.parseFloat(merchandiseVO.getMerMoney()));
                                po.setPayStartDate(now);
                                po.setPayStatus("1");
                                isOK = true;
                                payList.add(po);

                                String resultFormat =
                                        "<div>手机号码：%s 套餐：%s 原价格:%s元 折扣价格:%s元<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                                resultFormat =
                                        String.format(resultFormat, pos[0], pos[1], merchandiseVO.getMerMoney(),
                                                payMoney, "初始化成功");
                                sb.append(resultFormat);


                                break;
                            }
                        }
                        if (!isOK) {
                            String resultFormat =
                                    "<div>手机号码:%s 套餐:%s<span  style=\"color: red;margin-left: 10px;\">%s</span></div>";// 单条充值结果
                            resultFormat = String.format(resultFormat, pos[0], pos[1], "初始化失败，找不到对应的套餐");
                            sb.append(resultFormat);
                        } else {

                        }

                    }

                    Float sumPayMoney = 0f;
                    for (TbCzPayPO po : payList) {
                        sumPayMoney += po.getPayDiscountMoney();
                    }

                    if (money < sumPayMoney) {

                        setActionResult("1001", "您账户余额:" + money + " 本次批量充值需要金额:" + sumPayMoney + "，余额不足，请充值再操作");
                    } else {
                        setActionResult("0", "初始化充值数据成功");
                        addJsonObj("sumPayMoney", sumPayMoney);
                    }

                } else {
                    setActionResult("1001", "支付密码不正确");
                }

            } catch (SQLException e) {
                setActionResult("1913", "代理商充值数据错误");
                logger.error("代理商充值数据错误", e);
            } catch (Exception e) {
                logger.error("代理商充值数据错误", e);
                setActionResult("1913", "代理商充值数据错误，请输入正确的格式");
            } catch (BaseException e) {
                setActionResult("1913", "代理商充值数据错误，请输入正确的格式");
                logger.error("代理商充值数据错误", e);
            }
        }

        addJsonObj("result", sb.toString());
        doJsonOut();
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "操作成功", faileMsg = "操作失败"))
    public void addClientBatchPay() throws BaseException {

        String data = super.getReqeustObj().getParameter("data");
        JSONObject json = null;
        if (AssertUtil.isEmpty(data)) {
            logger.error("数据参数不能为空");
            throw new BaseException("1005", "数据参数不能为空");
        }

        try {
            json = JSONObject.fromObject(data);
        } catch (Exception e) {
            logger.error("json格式错误");
            throw new BaseException("1005", "json格式错误");
        }
        String userAccount = null;
        String userPassword = null;
        String payPassword = null;
        JSONArray mobiles = null;
        if (json.containsKey("userAccount")) {
            userAccount = json.getString("userAccount");
        } else {
            logger.error("userAccount 用户账号数据参数不能为空");
            throw new BaseException("1005", "userAccount 用户账号数据参数不能为空");
        }
        if (json.containsKey("userPassword")) {
            userPassword = json.getString("userPassword");
        } else {
            logger.error("userPassword 用户账号密码数据参数不能为空");
            throw new BaseException("1005", "userPassword 用户账号密码数据参数不能为空");
        }
        if (json.containsKey("payPassword")) {
            payPassword = json.getString("payPassword");
        } else {
            logger.error("payPassword 用户账号支付密码数据参数不能为空");
            throw new BaseException("1005", "payPassword 用户账号支付密码数据参数不能为空");
        }
        if (json.containsKey("mobiles")) {
            mobiles = json.getJSONArray("mobiles");
        } else {
            logger.error("mobile 充值号码数据参数不能为空");
            throw new BaseException("1005", "mobile 充值号码数据参数不能为空");
        }

        if (mobiles.size() == 0) {
            logger.error("mobiles 充值号码数据参数无数据");
            throw new BaseException("1005", "mobiles 充值号码数据参数无数据");
        }

        String mobileContent = "";

        for (int i = 0; i < mobiles.size(); i++) {
            try {
                JSONObject tmp = mobiles.getJSONObject(i);
                mobileContent += tmp.getString("moblie");
                mobileContent += " ";
                mobileContent += tmp.getString("type");
                mobileContent += "\n";
            } catch (Exception e) {
                logger.error("mobile 充值号码数据参数错误");
                throw new BaseException("1005", "mobile 充值号码数据参数错误");
            }
        }

        ArrayList<String> sb = new ArrayList<String>();// 充值结果总和

        TbCzMerchantVO merchant = null;
        try {
            merchant = merchantService.getMerchantByUserAccount(userAccount);
        } catch (SQLException e1) {
            logger.error("数据库数据错误");
            throw new BaseException("1005", "数据库数据错误");
        }
        if (AssertUtil.isEmpty(merchant)) {
            logger.error("userAccount 登陆账户不存在");
            throw new BaseException("1005", "userAccount 登陆账户不存在");
        }
        if (AssertUtil.isEmpty(merchant.getIsClient()) || "0".equals(merchant.getIsClient())) {
            logger.error("接口调用未开启，请与客服联系");
            throw new BaseException("1005", "接口调用未开启，请与客服联系");
        }
        if (!userPassword.equals(merchant.getPassword())) {
            logger.error("userPassword 登陆密码不准确");
            throw new BaseException("1005", "userPassword 登陆密码不准确");
        }
        if (payPassword.equals(merchant.getPayPassword())) {
            Float money = Float.valueOf(merchant.getMoney());// 余额

            List<TbCzMerchandiseVO> useMerchandise = null;
            try {
                useMerchandise = this.merchandiseService.getUseMerchandise();
            } catch (Exception e1) {
                logger.error("数据库数据错误");
                throw new BaseException("1005", "数据库数据错误");
            }
            List<TbCzPayPO> payList = new ArrayList<TbCzPayPO>();

            String content = mobileContent;
            Date now = new Date();
            String[] contents = content.split("\n");
            for (String string : contents) {
                String[] pos = string.split(" ");
                TbCzPayPO po = new TbCzPayPO();
                po.setPayMoblie(pos[0]);

                boolean isOK = false;
                for (TbCzMerchandiseVO merchandiseVO : useMerchandise) {
                    if (pos[1].equals(merchandiseVO.getMerName())) {
                        Float payMoney =
                                Float.parseFloat(merchandiseVO.getMerMoney()) * Float.valueOf(merchant.getDiscount());
                        payMoney = Float.valueOf(new DecimalFormat("0.00").format(payMoney));
                        po.setPayDiscountMoney(payMoney);
                        po.setPayMerchatId(merchant.getUserId());
                        po.setPayMerchandiseId(merchandiseVO.getMerId());
                        po.setPayOper(merchant.getUserName());
                        po.setPayOriginalMoney(Float.parseFloat(merchandiseVO.getMerMoney()));
                        po.setPayStartDate(now);
                        po.setPayStatus("1");
                        isOK = true;
                        payList.add(po);
                        break;
                    }
                }
                if (!isOK) {
                    String resultFormat = "%s,%s";// 单条充值结果// 单条充值结果
                    resultFormat = String.format(resultFormat, pos[0], "失败，找不到对应的套餐");
                    sb.add(resultFormat);
                }
            }

            Float sumPayMoney = 0f;
            for (TbCzPayPO po : payList) {
                sumPayMoney += po.getPayDiscountMoney();
            }

            if (money < sumPayMoney) {

                setActionResult("1001", "您账户余额:" + money + " 本次批量充值需要金额:" + sumPayMoney + "，余额不足，请充值再操作");
            } else {
                // 支付
                for (TbCzPayPO po : payList) {
                    try {
                        String maxOrder = this.payService.addPayExt(po);
                        String resultFormat = "%s,%s,%s";// 单条充值结果
                        resultFormat = String.format(resultFormat, maxOrder, po.getPayMoblie(), "充值成功");
                        sb.add(resultFormat);
                    } catch (Exception e) {
                        logger.error("代理商充值数据错误", e);
                        String resultFormat = "%s,%s";// 单条充值结果
                        resultFormat = String.format(resultFormat, po.getPayMoblie(), "充值失败");
                        sb.add(resultFormat);
                    } catch (BaseException e) {
                        logger.error("代理商充值数据错误", e);
                        String resultFormat = "%s,%s";// 单条充值结果
                        resultFormat = String.format(resultFormat, po.getPayMoblie(), "充值失败");
                        sb.add(resultFormat);
                    }

                }
                setActionResult("0", "充流量提交成功");
                addJsonObj("sumPayMoney", sumPayMoney);
            }

        } else {
            setActionResult("1001", "支付密码不正确");
        }

        addJsonArray("result", sb);
    }

    private boolean isAdmin() {
        boolean result = false;
        User user = (User) DqdpAppContext.getCurrentUser();

        try {
            List<TbDqdpRolePO> list = roleService.listRoleByUserId(user.getId());

            if (!AssertUtil.isEmpty(list)) {
                for (TbDqdpRolePO tbDqdpRolePO : list) {
                    String roleId = tbDqdpRolePO.getRoleId();
                    if (ConfigMgr.get("systemmgr", "adminRole", "0c7f6536-156d-468b-b81a-cfb5fd9918bc").equals(roleId)) {
                        result = true;
                        break;
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (BaseException e) {
            e.printStackTrace();
        }

        return result;
    }


    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "操作成功", faileMsg = "操作失败"))
    public void getOrderInfo() throws BaseException {

        String data = super.getReqeustObj().getParameter("data");
        JSONObject json = null;
        if (AssertUtil.isEmpty(data)) {
            logger.error("数据参数不能为空");
            throw new BaseException("1005", "数据参数不能为空");
        }

        try {
            json = JSONObject.fromObject(data);
        } catch (Exception e) {
            logger.error("json格式错误");
            throw new BaseException("1005", "json格式错误");
        }
        String userAccount = null;
        String userPassword = null;
        String orderId = null;
        if (json.containsKey("userAccount")) {
            userAccount = json.getString("userAccount");
        } else {
            logger.error("userAccount 用户账号数据参数不能为空");
            throw new BaseException("1005", "userAccount 用户账号数据参数不能为空");
        }
        if (json.containsKey("userPassword")) {
            userPassword = json.getString("userPassword");
        } else {
            logger.error("userPassword 用户账号密码数据参数不能为空");
            throw new BaseException("1005", "userPassword 用户账号密码数据参数不能为空");
        }

        if (json.containsKey("orderId")) {
            orderId = json.getString("orderId");
        } else {
            logger.error("orderId 订单号码数据参数不能为空");
            throw new BaseException("1005", "orderId 订单号码数据参数不能为空");
        }

        if (AssertUtil.isEmpty(orderId)) {
            logger.error("订单号不能为空");
            throw new BaseException("订单号不能为空");
        }
        TbCzMerchantVO merchant = null;
        try {
            merchant = merchantService.getMerchantByUserAccount(userAccount);
        } catch (SQLException e1) {
            logger.error("数据库数据错误");
            throw new BaseException("1005", "数据库数据错误");
        }
        if (AssertUtil.isEmpty(merchant)) {
            logger.error("userAccount 登陆账户不存在");
            throw new BaseException("1005", "userAccount 登陆账户不存在");
        }
        if (AssertUtil.isEmpty(merchant.getIsClient()) || "0".equals(merchant.getIsClient())) {
            logger.error("接口调用未开启，请与客服联系");
            throw new BaseException("1005", "接口调用未开启，请与客服联系");
        }
        if (!userPassword.equals(merchant.getPassword())) {
            logger.error("userPassword 登陆密码不准确");
            throw new BaseException("1005", "userPassword 登陆密码不准确");
        }

        try {
            TbCzPayClientVO po = this.payService.getTbCzPayClientByPayID(orderId);
            if (!AssertUtil.isEmpty(po)) {
                if (merchant.getUserId().equals(po.getPayMerchatId())) {
                    po.setPayMerchandiseId(null);
                    po.setPayMerchatId(null);
                    addJsonObj("TbCzPayPO", po);
                } else {
                    addJsonObj("TbCzPayPO", null);
                }
            } else {
                addJsonObj("TbCzPayPO", null);
            }


        } catch (Exception e) {
            logger.info("订单号查询出错", e);
            setActionResult("1913", "订单号查询出错");
        }


    }
}
